using System;
using GoogleAdMobAds;
using MonoTouch.UIKit;
using Microsoft.Xna.Framework;
using AdRotator.Model;

using System.Drawing;

namespace AdRotatorXNA
{ 
    internal class AdMobViewDelegate : GADBannerViewDelegate
    {
        public AdMobViewDelegate() : base() { }
        
        public event EventHandler AdViewLoaded;
        public event EventHandler AdViewFailed;
        
        /// <summary>
        /// Looks like the didFailTOReceiveAdWithError binding has the incorrect name...?
        /// </summary>
        public override void AdView (GADBannerView view, GADRequestError error)
        {
            if (AdViewFailed != null)
                AdViewFailed(this, new EventArgs());
        }
        public override void AdViewDidReceiveAd (GADBannerView view)
        {            
            if (AdViewLoaded != null)
                AdViewLoaded(this, new EventArgs());
        }
    }
    
    internal class GoogleAdMobComponent : AdComponent
    {
        private static UIViewController _rootViewController;
        private static GoogleAdMobComponent _instance;
        private static GADBannerView _currentAd = null;
        private static bool _initialized = false;
        private static float _contentScale = 1.0f;
        
        private static AdMobViewDelegate _bannerDelegate;
        
        private GoogleAdMobComponent (Game game)
            : base (game) { }
        
        public static GoogleAdMobComponent Current
        {
            get
            {
                if (AdRotatorXNAComponent.game == null)
                    return null;
                
                if (_instance == null)
                    _instance = new GoogleAdMobComponent(AdRotatorXNAComponent.game);
                        
                return _instance;
            }
        }
        
        public static void Initialize(Game _game, string applicationID)
        {
            if (_initialized)
                return;
            
            _initialized = true;
            
            _rootViewController = (UIViewController)AdRotatorXNAComponent.game.Services.GetService(typeof(UIViewController));
            _contentScale = 1.0f / _rootViewController.View.ContentScaleFactor;
            
            _bannerDelegate = new AdMobViewDelegate();
            
            _bannerDelegate.AdViewLoaded += (o, e) =>
            {
                if (_currentAd != null)
                    _instance.State = AdState.AdLoaded;
            };
            
            _bannerDelegate.AdViewFailed += (o, e) =>
            {
                if (_currentAd != null)
                    _instance.State = AdState.AdFailed;
            };
        }
        
        public override void UpdateAd(AdInformation adInfo)
        {
            if (_currentAd != null && adInfo.AppID == _currentAd.AdUnitID)
                return;
            
            AdInfo = adInfo;
            
            State = AdState.Initialized;
            
            _currentAd = new GADBannerView(new RectangleF(0, int.MinValue, adInfo.Width * _contentScale, adInfo.Height * _contentScale));
            _currentAd.Delegate = _bannerDelegate;
            _rootViewController.View.AddSubview(_currentAd);
            
            var req = new GADRequest();
            
            _currentAd.AdUnitID = AdInfo.AppID;
            
            _currentAd.RootViewController = _rootViewController;            
            
            _currentAd.LoadRequest(req);
        }
        
        protected override void OnEnabledChanged (object sender, EventArgs args)
        {
            if (!Enabled)
                RemoveCurrentControl();
            
            base.OnEnabledChanged (sender, args);
        }
        
        protected override void UnloadContent ()
        {
            RemoveCurrentControl();
            base.UnloadContent ();
        }
        
        private void RemoveCurrentControl()
        {
            if (_currentAd == null)
                return;
            
            State = AdState.NotInitialized;
            
            _currentAd.Delegate = null;
           
            _currentAd.RemoveFromSuperview();
            
            _currentAd = null;
        }
        
        public override void UpdatePosition(Vector2 newPos)
        {
            if (_currentAd == null)
                return;
            
            newPos *= _contentScale;
            
            _currentAd.Frame = new RectangleF( newPos.X, newPos.Y, AdInfo.Width * _contentScale, AdInfo.Height * _contentScale);
        }
    }
}

